/*
 * VHAssociationSeasonOverviewGrid.java
 * Created on 27 sept. 2009
 *
 * VirtualHockey Internet Platform
 * http://code.google.com/p/virtualhockey/
 *
 * Copyright (c) 2005-2009, Jens and Jan Janke (VirtualHockey Project)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package com.hockeo.vhweb.client.ui.widget;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SortDir;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.hockeo.vhweb.client.VHMain;
import com.hockeo.vhweb.client.mvc.VHController;
import com.hockeo.vhweb.client.res.VHResConstants;
import com.hockeo.vhweb.client.rpc.VHRpcCallback;
import com.hockeo.vhweb.client.rpc.VHRpcResultReceiver;
import com.hockeo.vhweb.client.ui.menu.VHClubInfoContextMenu;
import com.hockeo.vhweb.client.ui.menu.VHGridContextMenu;
import com.hockeo.vhweb.client.utils.VHJsData;
import com.hockeo.vhweb.client.utils.enums.VHJsContestType;

/**
 * Displays a table that contains the winners of all international and national major
 * competitions.
 *
 * @version $Id$
 * @author jjanke
 */
public class VHAllWinnersListGrid extends LayoutContainer implements VHRpcResultReceiver<List<VHJsData>>
{
  private static final String           COL_CATEGORY_ORDER  = "category_order";
  private static final String           COL_CONTEST_TYPE    = "contest_type";
  private static final String           COL_RECORD_ORDER    = "record_order";
  private static final String           COL_CATEGORY_HEADER = "category_header";
  private final VHGridContextMenu       d_ctxmenu;
  private final GroupingStore<VHJsData> d_store;
  private Grid<VHJsData>                d_grid;
  private VHJsData                      d_season            = null;

  /**
   * Builds a new season overview grid.
   *
   * @param controller the VH display controller
   * @param season the season for which to display the overview (leave <code>null</code>
   *          to retrieve data for the current season)
   * @param assoc the association for which to display the overview
   */
  public VHAllWinnersListGrid( VHController controller, VHJsData season )
  {
    d_season = season;
    d_store = new GroupingStore<VHJsData>();

    setLayout( new FitLayout() );
    buildGrid();
    add( d_grid );

    d_ctxmenu = new VHClubInfoContextMenu( controller, d_grid, "clubWinner_" );

    loadData();
  }

  public void setRpcData( List<VHJsData> listRecords, String strPurpose )
  {
    d_store.removeAll();

    // Iterate over all records and add required extra information
    //
    for ( VHJsData record : listRecords )
    {
      // add information about the contest type (league, cup, cl or wl)
      //
      String strContestId = record.getString( "contest_id" );

      if ( strContestId.equals( "EU1" ) )
      {
        record.set( COL_CONTEST_TYPE, VHJsContestType.CL.name() );
        record.set( COL_CATEGORY_HEADER, VHMain.getConstants().intContests() );
        record.set( COL_CATEGORY_ORDER, "1" );
        record.set( COL_RECORD_ORDER, "11" );
      }
      else if ( strContestId.equals( "EU2" ) )
      {
        record.set( COL_CONTEST_TYPE, VHJsContestType.WL.name() );
        record.set( COL_CATEGORY_HEADER, VHMain.getConstants().intContests() );
        record.set( COL_CATEGORY_ORDER, "1" );
        record.set( COL_RECORD_ORDER, "12" );
      }
      else if ( record.getString( "type" ).equals( "NATIONAL_LEAGUE" ) )
      {
        record.set( COL_CONTEST_TYPE, VHJsContestType.LEAGUE.name() );
        record.set( COL_CATEGORY_HEADER, record.getString( "clubWinner_association_name" ) );
        record.set( COL_CATEGORY_ORDER, "2" + record.getString( "clubWinner_association_name" ) );
        record.set( COL_RECORD_ORDER, "21" );
      }
      else
      {
        record.set( COL_CONTEST_TYPE, VHJsContestType.CUP.name() );
        record.set( COL_CATEGORY_HEADER, record.getString( "clubWinner_association_name" ) );
        record.set( COL_CATEGORY_ORDER, "2" + record.getString( "clubWinner_association_name" ) );
        record.set( COL_RECORD_ORDER, "22" );
      }
    }

    d_store.add( listRecords );

    // grouping and sorting
    //
    d_store.groupBy( COL_CATEGORY_ORDER );
    d_store.sort( COL_RECORD_ORDER, SortDir.ASC );
  }

  /**
   * Sets the season for which to display data and asks the table to reload itself.
   */
  public void setSeason( VHJsData season )
  {
    if ( d_season != null && d_season.getInt( "id" ) == season.getInt( "id" ) )
      return;

    d_season = season;
    loadData();
  }

  public VHJsData getSeason()
  {
    return d_season;
  }

  /**
   * Asks the server to return refreshed data.
   */
  private void loadData()
  {
    VHController.getBaseDataService().getAllMajorContestHistoryRecords( VHController.getLocale(),
        ( d_season != null ? d_season.getInt( "id" ) : null ), new VHRpcCallback<List<VHJsData>>( this, null ) );
  }

  private void buildGrid()
  {
    GridCellRenderer<VHJsData> renderer = new GridCellRenderer<VHJsData>() {
      public String render( VHJsData data, String strProperty, ColumnData config, int rowIndex, int colIndex,
          ListStore<VHJsData> store, Grid<VHJsData> grid )
      {
        if ( strProperty.equals( "clubWinner_image032Id" ) )
          return "<img src='ImageServlet?id=" + data.getInt( "clubWinner_image032Id" ) + "'/>";
        else if ( strProperty.equals( "clubWinner_country" ) )
        {
          String strTooltip = data.getString( "clubWinner_country_name" );
          return "<img src='images/flags/32x32/" + data.getString( strProperty ) + ".png' title='" + strTooltip + "'/>";
        }
        else if ( strProperty.equals( "clubWinner_name" ) )
        {
          String str = "<span style='font-size: larger;'>" + data.getString( strProperty );

          if ( !data.getString( COL_CONTEST_TYPE ).equals( VHJsContestType.LEAGUE.name() ) )
            str += " (" + data.getInt( "clubWinner_league_category" ) + ")";

          str += "</span";

          return str;
        }
        else if ( strProperty.equals( COL_RECORD_ORDER ) )
          return "<img src='images/contests/" + data.getString( COL_CONTEST_TYPE ).toLowerCase() + "_32.png'/>";

        return String.valueOf( data.get( strProperty ) );
      }
    };

    // Column definitions
    //
    VHResConstants constants = VHMain.getConstants();
    ArrayList<ColumnConfig> listCols = new ArrayList<ColumnConfig>();
    ColumnConfig col;

    col = new ColumnConfig();
    col.setId( COL_CATEGORY_ORDER );
    col.setWidth( 0 );
    col.setAlignment( HorizontalAlignment.RIGHT );
    col.setResizable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    col.setHidden( true );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( COL_RECORD_ORDER );
    col.setHeader( constants.contestTypeAbbrev() );
    col.setToolTip( constants.contestType() );
    col.setWidth( 42 );
    col.setAlignment( HorizontalAlignment.CENTER );
    col.setResizable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    col.setRenderer( renderer );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubWinner_country" );
    col.setHeader( constants.countryAbbrev() );
    col.setToolTip( constants.country() );
    col.setWidth( 42 );
    col.setRenderer( renderer );
    col.setAlignment( HorizontalAlignment.CENTER );
    col.setResizable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubWinner_image032Id" );
    col.setHeader( constants.clubLogoAbbrev() );
    col.setToolTip( constants.clubLogo() );
    col.setWidth( 42 );
    col.setRenderer( renderer );
    col.setAlignment( HorizontalAlignment.CENTER );
    col.setResizable( false );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    col = new ColumnConfig();
    col.setId( "clubWinner_name" );
    col.setHeader( constants.clubName() );
    col.setWidth( 180 );
    col.setRenderer( renderer );
    col.setMenuDisabled( true );
    col.setSortable( false );
    listCols.add( col );

    final ColumnModel cm = new ColumnModel( listCols );

    // Header cells with tooltips
    //
    GroupingView view = new GroupingView();

    view.setForceFit( true );
    view.setGroupRenderer( new GridGroupRenderer() {
      public String render( GroupColumnData data )
      {
        VHJsData recordFirst = (VHJsData) data.models.get( 0 );

        if ( recordFirst.getString( COL_CATEGORY_ORDER ).equals( "1" ) )
          return recordFirst.getString( COL_CATEGORY_HEADER );
        else
        {
          // Add the flag of the association
          //
          String strAssocId = recordFirst.getString( "clubWinner_association_id" );

          return "<span style='padding-left: 22px; background:url(images/flags/16x16/" + strAssocId + ".png) no-repeat 2px center;'>" + recordFirst.getString( COL_CATEGORY_HEADER ) + "</span>";
        }
      }
    } );

    // Grid
    //
    d_grid = new Grid<VHJsData>( d_store, cm );
    d_grid.setView( view );
    d_grid.setAutoExpandColumn( "clubWinner_name" );
    d_grid.setHideHeaders( false );
    d_grid.setStripeRows( true );
    d_grid.setBorders( true );
    d_grid.setAutoWidth( true );
  }
}
